package org.rabbitmq.test.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @program: Spring_RabbitMQ_Test
 * @author: chen yizhen
 * @create: 2025-03-11 10:55
 **/
@Configuration
public class MyRabbitConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 如果没有调用@RabbitListener(queues = "test.queue")，则需要手动调用RabbitAdmin
     * @return
     */
//    @Autowired
//    private ConnectionFactory connectionFactory;
//
//    @Bean
//    public RabbitAdmin rabbitAdmin() {
//        return new RabbitAdmin(connectionFactory);
//    }

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制RabbitTemplate
     * 1、服务器收到消息就回调
     * 2、queue接收到消息就回调
     * 3、消费端确认(保证每个消息被正确消费，此时才可以broker删除这个消息)
     *      默认是自动确认，只要消息被接受到，客户端会自动确认，服务端就会移除这个消息
     *          问题：
     *          如果发生宕机，会发生消息丢失
     */
    @PostConstruct
    public void initRabbitTemplate(){
        //设置确认回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *  1、只要消息抵达Boker,ack就返回true
             * @param correlationData 关联数据
             * @param ack 是否成功接收
             * @param cause 失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                /**
                 * 1、做好消息确认机制(publisher, consumer【手动ack】)
                 * 2、每一个发送的消息都在数据库做好记录，定期将失败的消息再次发送一遍
                 */
                System.out.println("confirm...correlationData["+ correlationData +"]==>ack["+ ack +"]==>cause["+cause+"]");
            }
        });

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             *
             * @param message 投递失败的消息详情原因
             * @param replyCode 回复的状态码
             * @param replyText 回复的文本内容
             * @param exchange 发给了哪个交换机
             * @param routingKey 消息发送的路由键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("Fail message["+message+"]==>replyCode["+replyCode+"]==>replyText["+replyText+"]==>exchange["+exchange+"]==>routingKey["+routingKey+"]");
            }
        });


    }
}
